package com.kancy.stream.rabbit.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kancy.stream.rabbit.exception.MessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;

/**
 * LogExceptionHandler
 *
 * @author kancy
 * @date 2020/3/8 19:29
 */
public class LogExceptionHandler implements ExceptionHandler {
    private static Logger log = LoggerFactory.getLogger(LogExceptionHandler.class);

    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 处理异常
     *
     * @param message
     * @param exception
     */
    @Override
    public void onException(Message message, Exception exception) {
        try {
            String errorMessage = String.format("消息处理异常：%s , message: %s",
                    exception.getMessage(), objectMapper.writeValueAsString(message));
            log.error(errorMessage, exception);
        } catch (JsonProcessingException e) {
            throw new MessageException(e);
        }
    }

}
